<?php

class messaging {

	private $userObj;

	private $requests = 0;
	private $messages = 0;

	const FROM_USER = 1;
	const FROM_GROUP = 2;
	const FROM_INSTITUTION = 3;

	public function __construct(user &$userObj){
		$this->userObj = $userObj;
	}
	
	public function getUnread(){
		$requests = $this->getGroupRequests();
		$messages = $this->getMessages();

		$messages = array("unreadCount" => $this->getUnreadCount(), "messages" => $messages, "requests" => $requests);
	
		return $messages;
	}
	
	public function getUnreadCount(){
		// Message count + group requests
		
		return $this->requests + $this->messages;
	}
	
	public function getGroupRequests(){
		$requests = $this->userObj->getAuthorisationRequests();
		
		// Get the numbers.
		foreach($requests as $groupRequest){
			$this->requests += count($groupRequest['pending']);
		}
		
		return $requests;
	}
	
	public function deleteMessage($msgID){
		$dbCon = db::singleton();
		
		$sql = "DELETE FROM " . SYS_DB_DBNAME . ".message WHERE msgID=" . (int)$dbCon->real_escape_string($msgID) . " AND to_uID=" . (int)$dbCon->real_escape_string($this->userObj->getuID());
		$dbCon->single($sql);
	}
	
	public function getMessages(){
		$dbCon = db::singleton();
		
		$sql = "SELECT * FROM " . SYS_DB_DBNAME . ".message WHERE to_uID=" . $this->userObj->getuID();
		
		$results = $dbCon->single($sql);
		
		$this->messages = count($results);
		
		return $results;
	}

	public function sendMessage($id, $type, $message, $sourceID, $from){
		if(is_integer($from) == false || is_integer($id) == false || is_integer($sourceID) == false) throw new PicBoardException('Source ID is not an integer.');
		
		$dbCon = db::singleton();
		
		switch($from){
			// From a user
			case 1:
				$sql = "INSERT INTO " . SYS_DB_DBNAME . ".message (to_uID, from_uID, type, message) VALUES(" . $dbCon->real_escape_string($id) . ", " . $dbCon->real_escape_string($sourceID) . ", '" . $dbCon->real_escape_string($type) . "', '" . $dbCon->real_escape_string($message) . "')";
			break;
			
			// From a group
			case 2:
				$sql = "INSERT INTO " . SYS_DB_DBNAME . ".message (to_uID, group_gID, type, message) VALUES(" . $dbCon->real_escape_string($id) . ", " . $dbCon->real_escape_string($sourceID) . ", '" . $dbCon->real_escape_string($type) . "', '" . $dbCon->real_escape_string($message) . "')";
			break;
			
			// From an institution
			case 3:
				$sql = "INSERT INTO " . SYS_DB_DBNAME . ".message (to_uID, institution_instID, type, message) VALUES(" . $dbCon->real_escape_string($id) . ", " . $dbCon->real_escape_string($sourceID) . ", '" . $dbCon->real_escape_string($type) . "', '" . $dbCon->real_escape_string($message) . "')";
			break;
		
		}
		
		$result = $dbCon->single($sql);
	}

}
?>